<template>
  <Layout>
    <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <form @submit.prevent="submitPost" class="space-y-6">
        <!-- 标题栏 -->
        <div class="bg-white rounded-lg shadow-md p-6">
          <h1 class="text-2xl font-bold text-gray-900 mb-6">写文章</h1>

          <!-- 文章标题 -->
          <div class="mb-4">
            <input
              v-model="form.title"
              type="text"
              placeholder="请输入文章标题..."
              class="w-full text-3xl font-bold border-0 border-b-2 border-gray-200 focus:border-blue-500 focus:outline-none pb-2"
              required
            />
          </div>

          <!-- 文章别名 -->
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-1">文章别名（URL）</label>
            <input
              v-model="form.slug"
              type="text"
              placeholder="article-slug"
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
            />
            <p class="text-sm text-gray-500 mt-1">留空将自动根据标题生成</p>
          </div>

          <!-- 文章摘要 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">文章摘要</label>
            <textarea
              v-model="form.excerpt"
              rows="3"
              placeholder="简要描述文章内容..."
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
            ></textarea>
          </div>
        </div>

        <!-- 文章内容 -->
        <div class="bg-white rounded-lg shadow-md p-6">
          <div class="flex justify-between items-center mb-4">
            <label class="text-lg font-semibold text-gray-900">文章内容</label>
            <div class="flex space-x-2">
              <button
                type="button"
                @click="editorMode = 'write'"
                class="px-3 py-1 text-sm rounded"
                :class="editorMode === 'write' ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-700'"
              >
                编辑
              </button>
              <button
                type="button"
                @click="editorMode = 'preview'"
                class="px-3 py-1 text-sm rounded"
                :class="editorMode === 'preview' ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-700'"
              >
                预览
              </button>
            </div>
          </div>

          <!-- 编辑器工具栏 -->
          <div v-if="editorMode === 'write'" class="border-b pb-2 mb-4">
            <div class="flex flex-wrap gap-2">
              <button type="button" @click="insertMarkdown('**', '**')" class="p-2 hover:bg-gray-100 rounded" title="粗体">
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                  <path d="M6 4v12h4.5a3.5 3.5 0 100-7H8V7h2.5a3.5 3.5 0 100-7H6v4z"/>
                </svg>
              </button>
              <button type="button" @click="insertMarkdown('*', '*')" class="p-2 hover:bg-gray-100 rounded" title="斜体">
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                  <path d="M8 4v12h4V4H8z" transform="skewX(-15)"/>
                </svg>
              </button>
              <button type="button" @click="insertMarkdown('# ', '')" class="p-2 hover:bg-gray-100 rounded" title="标题">
                <span class="font-bold">H</span>
              </button>
              <button type="button" @click="insertMarkdown('[', '](url)')" class="p-2 hover:bg-gray-100 rounded" title="链接">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"/>
                </svg>
              </button>
              <button type="button" @click="insertMarkdown('![', '](url)')" class="p-2 hover:bg-gray-100 rounded" title="图片">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/>
                </svg>
              </button>
              <button type="button" @click="insertMarkdown('```\n', '\n```')" class="p-2 hover:bg-gray-100 rounded" title="代码块">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"/>
                </svg>
              </button>
              <button type="button" @click="insertMarkdown('> ', '')" class="p-2 hover:bg-gray-100 rounded" title="引用">
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                  <path fill-rule="evenodd" d="M5 5a1 1 0 011-1h8a1 1 0 110 2H6a1 1 0 01-1-1zm0 4a1 1 0 011-1h8a1 1 0 110 2H6a1 1 0 01-1-1zm0 4a1 1 0 011-1h4a1 1 0 110 2H6a1 1 0 01-1-1z" clip-rule="evenodd"/>
                </svg>
              </button>
              <button type="button" @click="insertMarkdown('- ', '')" class="p-2 hover:bg-gray-100 rounded" title="列表">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/>
                </svg>
              </button>
            </div>
          </div>

          <!-- 内容编辑区 -->
          <div v-if="editorMode === 'write'">
            <textarea
              ref="contentEditor"
              v-model="form.content"
              rows="20"
              placeholder="开始写作..."
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500 font-mono"
              required
            ></textarea>
          </div>

          <!-- 预览区 -->
          <div v-else class="prose max-w-none min-h-[500px] p-4 border border-gray-200 rounded-md" v-html="markdownPreview">
          </div>
        </div>

        <!-- 文章设置 -->
        <div class="bg-white rounded-lg shadow-md p-6">
          <h2 class="text-lg font-semibold text-gray-900 mb-4">文章设置</h2>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <!-- 分类 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">分类</label>
              <select
                v-model="form.category_id"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="">选择分类</option>
                <option v-for="category in categories" :key="category.id" :value="category.id">
                  {{ category.name }}
                </option>
              </select>
            </div>

            <!-- 标签 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">标签</label>
              <div class="flex flex-wrap gap-2 mb-2">
                <span
                  v-for="tag in selectedTags"
                  :key="tag"
                  class="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm flex items-center"
                >
                  {{ tag }}
                  <button
                    type="button"
                    @click="removeTag(tag)"
                    class="ml-2 text-blue-600 hover:text-blue-800"
                  >
                    ×
                  </button>
                </span>
              </div>
              <input
                v-model="newTag"
                @keyup.enter="addTag"
                type="text"
                placeholder="输入标签，按回车添加"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              />
            </div>

            <!-- 特色图片 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">特色图片</label>
              <div class="flex items-center space-x-4">
                <img
                  v-if="form.featured_image_preview"
                  :src="form.featured_image_preview"
                  alt="特色图片预览"
                  class="w-20 h-20 object-cover rounded"
                />
                <div class="flex-1">
                  <input
                    type="file"
                    @change="handleImageChange"
                    accept="image/*"
                    class="hidden"
                    ref="imageInput"
                  />
                  <button
                    type="button"
                    @click="$refs.imageInput.click()"
                    class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300"
                  >
                    选择图片
                  </button>
                </div>
              </div>
            </div>

            <!-- 发布状态 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">发布状态</label>
              <select
                v-model="form.status"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="draft">草稿</option>
                <option value="published">发布</option>
                <option value="scheduled">定时发布</option>
              </select>
            </div>

            <!-- 访问权限 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">访问权限</label>
              <select
                v-model="form.access_level"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="public">公开</option>
                <option value="login_required">需要登录</option>
                <option value="followers_only">仅关注者</option>
                <option value="private">私密</option>
              </select>
            </div>

            <!-- 定时发布 -->
            <div v-if="form.status === 'scheduled'">
              <label class="block text-sm font-medium text-gray-700 mb-1">发布时间</label>
              <input
                v-model="form.published_at"
                type="datetime-local"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              />
            </div>

            <!-- 密码保护 -->
            <div v-if="form.access_level === 'private'">
              <label class="block text-sm font-medium text-gray-700 mb-1">访问密码</label>
              <input
                v-model="form.password"
                type="text"
                placeholder="设置访问密码"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
          </div>

          <!-- 其他设置 -->
          <div class="mt-6 space-y-4">
            <div class="flex items-center">
              <input
                id="allow_comments"
                v-model="form.allow_comments"
                type="checkbox"
                class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
              />
              <label for="allow_comments" class="ml-2 text-sm text-gray-700">
                允许评论
              </label>
            </div>

            <div class="flex items-center">
              <input
                id="is_featured"
                v-model="form.is_featured"
                type="checkbox"
                class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
              />
              <label for="is_featured" class="ml-2 text-sm text-gray-700">
                设为精选
              </label>
            </div>

            <div class="flex items-center">
              <input
                id="is_sticky"
                v-model="form.is_sticky"
                type="checkbox"
                class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
              />
              <label for="is_sticky" class="ml-2 text-sm text-gray-700">
                置顶文章
              </label>
            </div>
          </div>
        </div>

        <!-- SEO设置 -->
        <div class="bg-white rounded-lg shadow-md p-6">
          <h2 class="text-lg font-semibold text-gray-900 mb-4">SEO设置</h2>

          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">SEO标题</label>
              <input
                v-model="form.meta_title"
                type="text"
                placeholder="留空使用文章标题"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              />
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">SEO描述</label>
              <textarea
                v-model="form.meta_description"
                rows="3"
                placeholder="留空使用文章摘要"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              ></textarea>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">SEO关键词</label>
              <input
                v-model="form.meta_keywords"
                type="text"
                placeholder="用逗号分隔多个关键词"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="flex justify-between items-center">
          <div class="text-sm text-gray-500">
            <span v-if="autoSaveTime">自动保存于 {{ autoSaveTime }}</span>
          </div>
          <div class="flex space-x-3">
            <button
              type="button"
              @click="saveDraft"
              class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300"
            >
              保存草稿
            </button>
            <button
              type="button"
              @click="preview"
              class="px-4 py-2 bg-white text-blue-600 border border-blue-600 rounded-md hover:bg-blue-50"
            >
              预览
            </button>
            <button
              type="submit"
              :disabled="loading"
              class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
            >
              {{ loading ? '发布中...' : '发布文章' }}
            </button>
          </div>
        </div>
      </form>
    </div>
  </Layout>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { router } from '@inertiajs/inertia-vue3'
import Layout from '@/Components/Layout.vue'
import axios from 'axios'
import { marked } from 'marked'

const props = defineProps({
  categories: Array,
  tags: Array
})

const loading = ref(false)
const editorMode = ref('write')
const contentEditor = ref(null)
const newTag = ref('')
const selectedTags = ref([])
const autoSaveTime = ref('')
const autoSaveTimer = ref(null)

const form = reactive({
  title: '',
  slug: '',
  excerpt: '',
  content: '',
  category_id: '',
  featured_image: null,
  featured_image_preview: null,
  status: 'draft',
  access_level: 'public',
  password: '',
  published_at: '',
  allow_comments: true,
  is_featured: false,
  is_sticky: false,
  meta_title: '',
  meta_description: '',
  meta_keywords: ''
})

const markdownPreview = computed(() => {
  return marked(form.content || '')
})

const insertMarkdown = (before, after) => {
  const textarea = contentEditor.value
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const text = textarea.value
  const selected = text.substring(start, end)

  const replacement = before + selected + after
  form.content = text.substring(0, start) + replacement + text.substring(end)

  // 设置光标位置
  setTimeout(() => {
    textarea.focus()
    const newPos = start + before.length + selected.length
    textarea.setSelectionRange(newPos, newPos)
  }, 0)
}

const handleImageChange = (event) => {
  const file = event.target.files[0]
  if (!file) return

  if (file.size > 5 * 1024 * 1024) {
    alert('图片大小不能超过 5MB')
    return
  }

  form.featured_image = file

  const reader = new FileReader()
  reader.onload = (e) => {
    form.featured_image_preview = e.target.result
  }
  reader.readAsDataURL(file)
}

const addTag = () => {
  if (!newTag.value.trim()) return
  if (selectedTags.value.includes(newTag.value)) {
    alert('该标签已存在')
    return
  }

  selectedTags.value.push(newTag.value.trim())
  newTag.value = ''
}

const removeTag = (tag) => {
  const index = selectedTags.value.indexOf(tag)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  }
}

const autoSave = async () => {
  if (!form.title || !form.content) return

  try {
    const formData = new FormData()
    Object.keys(form).forEach(key => {
      if (key === 'featured_image' && form[key]) {
        formData.append('featured_image', form[key])
      } else if (key !== 'featured_image_preview') {
        formData.append(key, form[key])
      }
    })
    formData.append('tags', JSON.stringify(selectedTags.value))
    formData.append('auto_save', 'true')

    await axios.post('/api/posts/auto-save', formData)
    autoSaveTime.value = new Date().toLocaleTimeString()
  } catch (error) {
    console.error('自动保存失败:', error)
  }
}

const saveDraft = async () => {
  form.status = 'draft'
  await submitPost()
}

const preview = () => {
  // 实现预览功能
  const previewData = { ...form, tags: selectedTags.value }
  localStorage.setItem('post_preview', JSON.stringify(previewData))
  window.open('/posts/preview', '_blank')
}

const submitPost = async () => {
  loading.value = true

  try {
    const formData = new FormData()
    Object.keys(form).forEach(key => {
      if (key === 'featured_image' && form[key]) {
        formData.append('featured_image', form[key])
      } else if (key !== 'featured_image_preview') {
        formData.append(key, form[key])
      }
    })
    formData.append('tags', JSON.stringify(selectedTags.value))

    const response = await axios.post('/api/posts', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    // 成功后跳转
    if (form.status === 'published') {
      router.visit(`/posts/${response.data.slug}`)
    } else {
      router.visit('/profile/posts')
    }
  } catch (error) {
    console.error('发布失败:', error)
    alert('发布失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  // 启动自动保存
  autoSaveTimer.value = setInterval(autoSave, 30000) // 每30秒自动保存
})

onUnmounted(() => {
  // 清理定时器
  if (autoSaveTimer.value) {
    clearInterval(autoSaveTimer.value)
  }
})
</script>